#coding=utf8
import threading, thread, os, sys
import time
from cmrhelper import GbkToUtf8, UtfToGbk

l=thread.allocate_lock()
class PicQueue(object):
    "The queue for download"
    def __init__(self):
        self.pics = []
    def pushpic(self,content):
        l.acquire()
        self.pics.append(content)
        l.release()
    def poppic(self):
        l.acquire()
        if len(self.pics) > 0:
            s = self.pics[0]
            del self.pics[0]
            l.release()
            return s
        else:
            l.release()
            return None
    def getlens(self):
        l.acquire()
        x = len(self.pics)
        l.release()
        return x

def ExportList(queue, config, name='uname'):
    "ExportLists"
    name += '.txt'
    explst = ''
    while queue.getlens():
        for item in queue.poppic():
            explst += item
            explst += '\t'
        if config.win:
            explst += '\r\n'
        else:
            explst += '\n'
    WriteFoFile(explst, os.path.join(os.getcwd(), 'list', name), config)
    return explst

def WriteFoFile(buf, path, config):
    try:
        if config.win:
            path = UtfToGbk(path)
        f = open(path, 'w')
        f.write(buf)
        f.close()
    except  Exception, e:
        if f and (not f.closed):
            f.close()
        raise
    
class Downloader(threading.Thread):
    def __init__(self, picqueue, name, config):
        threading.Thread.__init__(self)
        self.config = config
        self.picqueue = picqueue
        self.name = name
        self.end = False
    def run(self):
        "auto download pics from queue"
        while True and not self.end:
            if self.picqueue.getlens() > 0:
                self.download(self.picqueue.poppic())
            else:
                time.sleep(1)
        print 'downthread',self.name,'exit'
    def download(self,picitem):
        if not picitem:
            return
        url = picitem[0]
        referer = picitem[1]
        chaptername = picitem[2]
        manganame = picitem[3]
        # gbk for windows ,utf-8 for linux file system
        # rough code ^_^
        spath = os.path.join(self.config.savepath, manganame, chaptername)
        if self.config.win:
            spath = spath.decode('utf-8').encode('gbk')
        if os.path.isfile(os.path.join(spath, url[url.rfind('/')+1:])):
            # exist
            print os.path.join(spath, url[url.rfind('/')+1:]),'exists, abort.'
            return
        else:
            # dostr = "\"%s\" \"%s\" -q --referer=\"%s\" -P \"%s\"" % (self.config.wgetpath, url, referer, spath)
            dostr = "%s \"%s\" -t 5 -q --referer=\"%s\" -P \"%s\"" %\
                (self.config.wgetpath, url, referer, spath)
            print dostr
            os.system(dostr)
            print url,'download.'
